import cv2
import numpy as np
import os
import face_recognition
import time
import pickle


class face_detector():
    def __init__(self,eye_cascade,face_cascade,results=[]):
        self.eye_cascade = eye_cascade
        self.face_cascade = face_cascade
        self.image_extensions = ['png', 'jpg', 'jpeg', 'gif']
        self.process_this_frame = True
        self.location = 'results.pkl'
        if len(results) >0:
            self.results = self.load_weigth()
        else:
            self.results = results


    def countFace_simple(self,frame):
        i=frame
        gray=cv2.cvtColor(i,cv2.COLOR_BGR2GRAY)
        faces=self.face_cascade.detectMultiScale(gray,1.3,5)
        return len(faces)

    def load_weigth(self):
        if os.path.exists(self.location):
            with open(self.location,'rb') as f:
                results = pickle.load(f)

        else:
            results = self.save_weigth(self.location)
        return results

    def save_weigth(self):
        results = self.load_faces("./images/")
        with open(self.location, 'wb') as f:
            pickle.dump(results, f)


    def load_faces(self, path):
        print("loading training data")
        image_extensions = self.image_extensions
        names = [i for i in os.listdir(path) if "." not in i]
        known_names = []
        known_encodings = []
        for name in names:
            sub_path = os.path.join(path, name)
            for image_name in os.listdir(sub_path):
                if image_name.rsplit(".")[1].lower() in image_extensions:
                    load_image = face_recognition.load_image_file(os.path.join(sub_path, image_name))
                    face_feature = face_recognition.face_encodings(load_image)
                    if len(face_feature) > 0:
                        image_face_encoding = face_feature[0]
                        known_names.append(name)
                        known_encodings.append(image_face_encoding)
        return known_names, known_encodings

    def countFace(self):
        cap = cv2.VideoCapture(0)
        ret, frame = cap.read()
        rgb_frame = frame[:, :, ::-1]
        known_names = self.results[0]
        known_encodings = self.results[1]
        if self.process_this_frame:
            face_locations = face_recognition.face_locations(rgb_frame)  # 获得所有人脸位置
            face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)  # 获得人脸特征值
            face_names = []
            for face_encoding in face_encodings:
                matches = face_recognition.compare_faces(known_encodings, face_encoding, tolerance=0.5)
                if True in matches:
                    first_match_index = matches.index(True)
                    name = known_names[first_match_index]
                else:
                    name = "unknown"
                face_names.append(name)
            return face_names

    def getFaces(self,ts=2):
        init = time.time()
        faces =[]
        while True:
            faces.append(self.countFace())
            if time.time() - init >ts:
                faces.sort(reverse=True)
                return faces[0]


if __name__ =='__main__':
    with open("results.pkl", 'rb') as f:
        results = pickle.load(f)
    eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml")
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
    fd = face_detector(eye_cascade,face_cascade,results)
    print(fd.getFaces())